import tables, ConfigParser
from model import Select, Update
from common import C
from gamedata import *



import time

command_queue = []
flag = 1

Update = Update()
Select = Select()

config = ConfigParser.ConfigParser()
config.read("eris.conf")

def pop_all(session): 
    # delete everything from the stack
    for each in command_queue:
        if each[1] == session.p_id:
            command_queue.remove(each)


class EDActions:
    
    def checkConsciousness (self, *args):
        allConscious = 1

        for each in args:
            if (self.sessions[each].damage >= self.sessions[each].unconscious_rating):
                allConscious = None  

        return allConscious
    
    def halfRound(self, aID, dID):
            attackerWeaponDamage = 3 # default value for now
            appliedDamage = 0
            armorDefeatingHit = 0 #false
            attackRoll = stepRoller(self.sessions[aID].dexterity)
            if attackRoll >= (self.sessions[dID].physical_defense):
                # a hit, but how good?
                if (testResult(self.sessions[dID].physical_defense, attackRoll)) == 'extraordinary':
                    armorDefeatingHit = 1
                    self.sessions[aID].pushline("You skillfully bypass the defender's armor!")
                    self.sessions[dID].pushline("Your attacker bypassed your armor!")
                    
                if armorDefeatingHit != 1:
                    appliedDamage = attackerWeaponDamage - self.sessions[dID].normal_armor
                else:
                    appliedDamage = attackerWeaponDamage
                
                if appliedDamage > 0:
                    self.sessions[dID].damage += appliedDamage
                    
                #defender.msgTo("{actor} go down to {total} hitpoints.", total=defender.damage)            
                if appliedDamage <= 0:
                    self.sessions[aID].pushline("You hit your vicitim but their armor absorbed all the damage.")
                else:
                    self.sessions[aID].pushline("You hit your vicitim for %i damage." % appliedDamage)
                    #if checkConsciousness(defender) == None:
                        #(gv.characters[attacker]).writeLine("Your victim falls unconscious")
                        #(gv.characters[attacker]).writePromptOnly()
                    self.sessions[dID].pushline("%s hit you for %i damage." % (str.capitalize(self.sessions[aID].pname), appliedDamage))
                    self.sessions[dID].pushline("You have %i life points left." % (  self.sessions[dID].unconscious_rating - self.sessions[dID].damage))
            else:
                self.sessions[aID].pushline("You miss.")
                self.sessions[dID].pushline("You evade the attack from %s." % str.capitalize(self.sessions[aID].pname))
        

    def do_kill(self, session, target):
        aID = session.p_id # attacker
        for each in self.sessions:
            if self.sessions[each].pname == str.capitalize(target):
                dID = self.sessions[each].p_id # defender
        if not(vars().has_key('dID')):
            # target doesn't exist
            session.pushline("You don't see %s here!" % target)
            return
        
        # check if both are in same room
        if (self.sessions[aID].is_in != self.sessions[dID].is_in):
            session.pushline("You don't see %s here!" % target)
            return
        
        # check if both are conscious (or against anything else which could prevent action)
        if not self.checkConsciousness(aID):
            session.pushline("You not in any condition for combat!")
            return
            
        if not self.checkConsciousness(dID):
            session.pushline("You decide to show mercy on %s's unconscious body." % target)
            return
            
        # roll for initiative
        aInitiative = stepRoller(self.sessions[aID].initiative)
        bInitiative = stepRoller(self.sessions[dID].initiative)
        
        #attacker wins ties
        if aInitiative >= bInitiative:
            self.halfRound(aID, dID)
            if self.checkConsciousness(dID):
                self.halfRound(dID, aID)
        else:
            self.halfRound(dID, aID)
            if self.checkConsciousness(aID):
                self.halfRound(aID, dID)
        
        # report any knockouts/deaths
        for each in [aID, dID]:
            if self.sessions[each].damage >= self.sessions[each].death_rating:
                self.sessions[each].pushline("You have been killed!")
            elif not self.checkConsciousness(each):
                self.sessions[each].pushline("You have been knocked out cold!")
                

        
    def do_flee(self, session, target):
        session.pushline("You stop attacking %s." % target)    
        #while player actions are on the list, pop off action (regardless of what it is)
        for each in command_queue:
            if each[1] == session.p_id:
                command_queue.remove(each)

    def do_cast(self, session, target):
        session.pushline("You cast a %s at %s at %s." % (   target.split()[0],    target.split()[2],   str(time.time()) ))
        print "cast fired at %s" % time.asctime()

        
    def pop_all(self, session): 
        # delete everything from the stack
        for each in command_queue:
            if each[1] == session.p_id:
                command_queue.remove(each)


    def do_heal(self, session, line):
        #check if recovery test available
        # delete 1 test
        # subtract toughness roll from damage
        if session.recovery_tests_left <= 0:
            session.pushline("You do not have any available recovery tests.  Please try again later.")
            return
        elif session.damage == 0:
            session.pushline("You are not injured -- no need to recover.")
            return
        else:
            session.recovery_tests_left =  session.recovery_tests_left - 1
            healAmount = stepRoller(session.toughness)
            if session.damage < healAmount:
                healAmount = session.damage
                session.damage = 0
            else:
                session.damage = selssion.damage - healAmount
            session.pushline("You recover %i life points.  You current damage is %i." % (healAmount, session.damage))
             

             
        
        
        
        
    def do_sheet(self, session, line):

        #ch.writeLine("GENERAL INFO                          ATTRIBUTES")
        #ch.writeLine("Name: %sPhysical    Value/Step/Dice" % (ch.name.ljust(32)))
        #ch.writeLine("Race: %sPassion: %sDexterity   %s/ %s/ %s" % (ch.race.ljust(11), ch.passion.ljust(13), str(ch.attributes['dexterity'][0]).ljust(3), str(ch.attributes['dexterity'][1]).ljust(4), stepDice(ch.attributes['dexterity'][1])))
        #ch.writeLine("Sex: %sAge: %sStrength    %s/ %s/ %s" % (ch.sex.ljust(12), str(ch.age).ljust(17), str(ch.attributes['strength'][0]).ljust(3), str(ch.attributes['strength'][1]).ljust(4), stepDice(ch.attributes['strength'][1])))
        #ch.writeLine("Discipline: %sToughness   %s/ %s/ %s" % (ch.discipline.ljust(27), str(ch.attributes['toughness'][0]).ljust(3), str(ch.attributes['toughness'][1]).ljust(4), stepDice(ch.attributes['toughness'][1])))
        #ch.writeLine("Circle: %sMental" % (str(ch.circle).ljust(30)))
        #ch.writeLine("Total Legend: %sPerception  %s/ %s/ %s" % (str(ch.legend['total']).ljust(25), str(ch.attributes['perception'][0]).ljust(3), str(ch.attributes['perception'][1]).ljust(4), stepDice(ch.attributes['perception'][1])))
        #ch.writeLine("Unspent Legend: %sWillpower   %s/ %s/ %s" % (str(ch.legend['unspent']).ljust(23), str(ch.attributes['willpower'][0]).ljust(3), str(ch.attributes['willpower'][1]).ljust(4), stepDice(ch.attributes['willpower'][1])))
        #ch.writeLine("Devotion Points: %sCharisma    %s/ %s/ %s" % (str(ch.legend['devotion']).ljust(22), str(ch.attributes['charisma'][0]).ljust(3), str(ch.attributes['charisma'][1]).ljust(4), stepDice(ch.attributes['charisma'][1])))
        #ch.writeLine("") #Unspent Legend: %s     Devotion Points: %i" % (str(ch.legend['unspent']).ljust(40), ch.legend['devotion']))
        #ch.writeLine("COMBAT STATISTICS")
        #ch.writeLine("Physical Defense Value  %s/ XXX          KARMA" % (str(ch.combat['physical'][0]).ljust(4)))
        #ch.writeLine("Spell Defense Value     %s/ XXX           Current: %s" % (str(ch.combat['spell'][0]).ljust(4), str(ch.karma['current'])))
        #ch.writeLine("Social Defense Value    %sMaximum: %s" % (str(ch.combat['social']).ljust(20), str(ch.karma['max'])))
        #ch.writeLine("Normal/Mystical Armor   XXX / XXX           Cost:    %s" % (str(ch.karma['cost'])))
        #ch.writeLine("Flying Combat /Normal   %s/ %sKarma Dice: %s" % (str(ch.combat['flying'][0]).ljust(3), str(ch.combat['flying'][1]).ljust(14), str(ch.karma['cost'])))
        #ch.writeLine("Movement Combat/Normal  %s/ %s" % (str(ch.combat['movement'][0]).ljust(3), str(ch.combat['movement'][1]).ljust(14)))
        #ch.writeLine("Max. Carry/Max. Lift    %s/ %s" % (str(ch.combat['maxCarry']).ljust(3), str(ch.combat['maxLift']).ljust(14)))
        #ch.writeLine("Initiative Step & Dice  %s/ %s" % (str(ch.combat['initiative'][0]).ljust(3), stepDice(ch.combat['initiative'][0])))
        #ch.writeLine("")
        #ch.writeLine("DAMAGE  Blood Magic   WOUNDS     UNCONSCIOUS RATING     RECOVERY TESTS")
        #ch.writeLine("%s%s%s%s%s" % (str(ch.damage['damage']).ljust(8), str(ch.damage['bloodMagic']).ljust(14), str(ch.damage['wounds']).ljust(11), str(ch.damage['unconsciousRating']).ljust(23), str(ch.damage['recoveryTests'])))
        #ch.writeLine("")
        #ch.writeLine("WOUND THRESHOLD   DEATH RATING   RECOVERY DICE")
        #ch.writeLine("%s%s%s" % (str(ch.damage['WoundThreshold']).ljust(18), str(ch.damage['deathRating']).ljust(15), str(ch.damage['recoveryDice'])))
        #
        
        #self.test = (pname, self.email, self.truepass, self.salty, 0, self.description, self.ansi, self.discipline, self.circle, \
         #self.race, self.gender, self.age, self.spouse_name, self.dexterity, self.strength, self.toughness, self.perception, \
         #self.willpower, self.charisma, self.initiative, self.fly, self.max_carry, self.max_lift, self.physical_defense, \
         #self.spell_defense, self.social_defense, self.normal_armor, self.mystical_armor, self.wound_threshold, self.damage, \
         #self.wound, self.unconscious_rating, self.death_rating, self.blood_magic_cost, self.recovery_tests_left, \
         #self.recovery_tests_total, self.karma_dice, self.karma_current, self.karma_max, self.legend_unspent, self.legend_total, \  stepDice(attributeStep(session.strength))
         #self.passion)
        
        session.pushline("GENERAL INFO                          ATTRIBUTES")
        session.pushline("Name: %sPhysical    Value/Step/Dice" % (session.pname.ljust(32)))
        session.pushline("Race: %sPassion: %sDexterity   %s/ %s/ %s" % (session.race.ljust(11), session.passion.ljust(13), str(session.dexterity).ljust(3), str(attributeStep(session.dexterity)).ljust(4), stepDice(attributeStep(session.dexterity))))
        session.pushline("Sex: %sAge: %sStrength    %s/ %s/ %s" % (session.gender.ljust(12), str(session.age).ljust(17), str(session.strength).ljust(3), str(attributeStep(session.strength)).ljust(4), stepDice(attributeStep(session.strength))))
        session.pushline("Discipline: %sToughness   %s/ %s/ %s" % (session.discipline.ljust(27), str(session.toughness).ljust(3), str(attributeStep(session.toughness)).ljust(4), stepDice(attributeStep(session.toughness))))
        session.pushline("Circle: %sMental" % (str(session.circle).ljust(30)))
        session.pushline("Total Legend: %sPerception  %s/ %s/ %s" % (str(session.legend_total).ljust(25), str(session.perception).ljust(3), str(attributeStep(session.perception)).ljust(4), stepDice(attributeStep(session.perception))))
        session.pushline("Unspent Legend: %sWillpower   %s/ %s/ %s" % (str(session.legend_unspent).ljust(23), str(session.willpower).ljust(3), str(attributeStep(session.willpower)).ljust(4), stepDice(attributeStep(session.willpower))))
        session.pushline("Devotion Points: %sCharisma    %s/ %s/ %s" % (str(0).ljust(22), str(session.charisma).ljust(3), str(attributeStep(session.charisma)).ljust(4), stepDice(attributeStep(session.charisma))))
        session.pushline("") #Unspent Legend: %s     Devotion Points: %i" % (str(session.legend['unspent']).ljust(40), session.legend['devotion']))
        session.pushline("COMBAT STATISTICS      Value/Armor Defeating")
        session.pushline("Physical Defense Value  %s/ XX           KARMA" % (str(session.physical_defense).ljust(3)))
        session.pushline("Spell Defense Value     %s/ XX            Current: %s" % (str(session.spell_defense).ljust(3), str(session.karma_current)))
        session.pushline("Social Defense Value    %sMaximum: %s" % (str(session.social_defense).ljust(19), str(session.karma_max)))
        session.pushline("Normal/Mystical Armor   %s/ %s           Cost:    %s" % (str(session.normal_armor).ljust(3), str(session.mystical_armor).ljust(3), str(10)))
        session.pushline("Flying Combat/Normal    %s/ %sKarma Dice: %s" % ('NA'.ljust(3), 'NA'.ljust(14), 'd' + str(session.karma_dice)))
        session.pushline("Movement Combat/Normal  %s/ %s" % ('NA'.ljust(3), 'NA'.ljust(14)))
        session.pushline("Max. Carry/Max. Lift    %s/ %s" % (str(session.max_carry).ljust(3), str(session.max_lift).ljust(14)))
        session.pushline("Initiative Step & Dice  %s/ %s" % (str(session.initiative).ljust(3), stepDice(session.initiative)))
        session.pushline("")
        session.pushline("DAMAGE  Blood Magic   WOUNDS     UNCONSCIOUS RATING     RECOVERY TESTS")
        session.pushline("%s%s%s%s%s" % (str(session.damage).ljust(8), str(session.blood_magic_cost).ljust(14), str(session.wound).ljust(11), str(session.unconscious_rating).ljust(23), str(session.recovery_tests_total)))
        session.pushline("")
        session.pushline("WOUND THRESHOLD   DEATH RATING   RECOVERYS LEFT")
        session.pushline("%s%s%s" % (str(session.wound_threshold).ljust(18), str(session.death_rating).ljust(15), str(session.recovery_tests_left)))
        

    
    def doCreateCharacterRace(self, line):
        "Select character race"
        if line:
            if line in ["dwarf", "elf", "human", "obsidiman", "ork", "troll", "t\'skrang", "windling"]:
                self.insertStatement = self.insertStatement + '%s\',\'' % (string.replace(line,"'","\\'"))
                self.race = line
    
                if self.race == 'dwarf':
                    self.statMod = {'d':0, 's':2, 't':3, 'p':0, 'w':0, 'c':-1}
                
                elif self.race == 'elf':
                    self.statMod = {'d':2, 's':0, 't':-2, 'p':1, 'w':1, 'c':1}
                    
                elif self.race == 'human':
                    self.statMod = {'d':0, 's':0, 't':0, 'p':0, 'w':0, 'c':0}
                
                elif self.race == 'obsidiman':
                    self.statMod = {'d':-2, 's':6, 't':4, 'p':-1, 'w':0, 'c':-1}
                
                elif self.race == 'ork':
                    self.statMod = {'d':-1, 's':3, 't':1, 'p':0, 'w':-1, 'c':-1}
                    
                elif self.race == 'troll':
                    self.statMod = {'d':0, 's':4, 't':2, 'p':-1, 'w':1, 'c':0}
                
                elif self.race == 't\'skrang':
                    self.statMod = {'d':1, 's':0, 't':1, 'p':0, 'w':0, 'c':1}
                    
                elif self.race == 'windling':
                    self.statMod = {'d':1, 's':-4, 't':-3, 'p':1, 'w':0, 'c':2} 
    
                
                self.setState(self.doCreateCharacterSex)
            else:
                self.sendLine('Please enter a race - dwarf, elf, human, obsidiman, ork, troll, t\'skrang or windling ')
        else:
            self.sendLine('Please enter a race - dwarf, elf, human, obsidiman, ork, troll, t\'skrang or windling ')
    doCreateCharacterRace.prompt = 'Please enter the RACE for your character\nYour choices are dwarf, elf, human, obsidiman, ork, troll, t\'skrang or windling'
    
    def doCreateCharacterSex(self, line):
        "Create a new character password for the game"
        if line:
            if line in ["m", "f", "male", "female"]:
                if line in ["m", "f"]:
                    self.insertStatement = self.insertStatement + '%s\',\'' % (line)
                    self.setState(self.doCreateCharacterPassion)
                elif line == "male":
                    self.insertStatement = self.insertStatement + 'm\',\''
                    self.setState(self.doCreateCharacterPassion)
                else:
                    self.insertStatement = self.insertStatement + 'f\',\''
                    self.setState(self.doCreateCharacterPassion)
            else:
                self.sendLine('Please enter the sex of your character (m/f)')
        else:
            self.sendLine('Please enter the sex of your character (m/f)')
    doCreateCharacterSex.prompt = 'Is your character a male or female (m/f)'
    
    def doCreateCharacterPassion(self, line):
        "Choose Passion"
        if line:
            if line in ["Chorrolis", "Dis", "Floranuus", "Garlen", "Jaspree", "Lochost", \
                        "Mynbruje", "Raggok", "Thystonius", "Upandal", "Vestrial", "none"]:
                self.insertStatement = self.insertStatement + '%s\',\'' % (line)
                self.setState(self.doCreateCharacterDiscipline)
            else:
                self.sendLine('Please enter the Passion your character worships.  Your choices are\nChorrolis \
                                   \nDis\nFloranuus\nGarlen\nJaspree\nLochost\nMynbruje\nRaggok\nThystonius \
                                   \nUpandal\nVestrial\nnone\n(you can change this later if your unsure)')
        else:
            self.sendLine('Please enter the Passion your character worships.  Your choices are\nChorrolis \
                                   \nDis\nFloranuus\nGarlen\nJaspree\nLochost\nMynbruje\nRaggok\nThystonius \
                                   \nUpandal\nVestrial\nnone\n(you can change this later if your unsure)')
    doCreateCharacterPassion.prompt = 'Please enter the Passion your character worships.  Your choices are\nChorrolis \
                                   \nDis\nFloranuus\nGarlen\nJaspree\nLochost\nMynbruje\nRaggok\nThystonius \
                                   \nUpandal\nVestrial\nnone\n(you can change this later if your unsure)'
    
    
    def doCreateCharacterDiscipline(self, line):
        "Create a new character password for the game"
        if line:
            if line in ["air sailor", "archer", "beastmaster", "cavalryman", "elementalist", "illusionist", \
                        "nethermancer", "scout", "sky raider", "swordmaster", "thief", "troubadour", \
                        "warrior", "weaponsmith", "wizard"]:
                self.insertStatement = self.insertStatement + '%s\',\'' % (line)
                # set up minimums/maximums
                #'obsidiman': {'s':(9,18)},
                #'troll': {'s':(7,18), 't':(9,18)},
                #'windling': {'s':(2,15)}
                #if self.race in ["obsidiman", "troll", "windling"]:
                if self.race == 'dwarf':
                    self.stats['c'] = 3
                    self.stats['points'] -= 1
                elif self.race == 'elf':
                    self.stats['t'] = 4
                    self.stats['points'] -= 5
                elif self.race == 'obsidiman':
                    self.stats['d'] = 4
                    self.stats['p'] = 3
                    self.stats['c'] = 3
                    self.stats['s'] = 9
                    self.stats['points'] -= 11
                elif self.race == 'troll':
                    self.stats['p'] = 3
                    self.stats['s'] = 7
                    self.stats['t'] = 9
                    self.stats['points'] -= 5
                else: # must be 'windling':
                    self.stats['s'] = 6
                    self.stats['t'] = 5
                    self.stats['points'] -= 13
                    
                
                self.sendLine('Now your character attributes must be created.  The following table will assist you\n \
                                    Attribute   Purchase    Attribute   Purchase\n \
                                    Value       Points      Value       Points\n \
                                       2           +3          11          6\n \
                                       3           +2          12          8\n \
                                       4           +1          13         10\n \
                                       5            0          14         13\n \
                                       6            1          15         16\n \
                                       7            2          16         19\n \
                                       8            3          17         21\n \
                                       9            4          18         23\n \
                                      10            5\
                                    \nSetting all values to the minimum for your race, you now have \
                                    \nDexterity:  %i (%i)   Strength:  %i (%i)  Toughness: %i (%i)\
                                    \nPerception: %i (%i)   Willpower: %i (%i)  Charisma:  %i (%i)\
                                    \nYou have %i points left to spend. \
                                    \nSet attribute total using "s X" where s is the first letter  \
                                    \nof the attribute and X is the new value. \
                                    \nExample: c 15 would set charisma at 15 and cost you 16 purchase points \
                                    \nNote: if you lower a score - purchase points are "recovered" \
                                    \nNumbers in parentheses () are the attributes modified for your race \
                                    \nPlease enter an attribute modification (s 15), "table", or "done"' \
                                    % (self.stats['d'], (self.stats['d']+ self.statMod['d']), self.stats['s'], \
                                        (self.stats['s']+ self.statMod['s']), self.stats['t'], (self.stats['t']+ self.statMod['t']), \
                                        self.stats['p'],(self.stats['p']+ self.statMod['p']), self.stats['w'],\
                                        (self.stats['w']+ self.statMod['w']), self.stats['c'],(self.stats['c']+ self.statMod['c']), \
                                        self.stats['points']))
                self.setState(self.doCreateCharacterStats)
            else:
                self.sendLine('Please enter your character\'s discipline.  Your choices are\n \
                               air sailor\narcher\nbeastmaster\ncavalryman\nelementalist\n \
                               illusionist\nnethermancer\nscout\nsky raider\nswordmaster\n \
                               thief\ntroubadour\nwarrior\nweaponsmith\nwizard\n')
    doCreateCharacterDiscipline.prompt = 'Please enter your character\'s discipline.  Your choices are \
                                         \nair sailor\narcher\nbeastmaster\ncavalryman\nelementalist \
                                         \nillusionist\nnethermancer\nscout\nsky raider\nswordmaster \
                                         \nthief\ntroubadour\nwarrior\nweaponsmith\nwizard'
    
    def doCreateCharacterStats(self, line):
        "Create a new character name for the game"
        if line:
            if line == 'table':
                self.sendLine('Attribute   Purchase    Attribute   Purchase \
                                \nValue       Points      Value       Points \
                                \n   2           +3          11          6 \
                                \n   3           +2          12          8 \
                                \n   4           +1          13         10 \
                                \n   5            0          14         13 \
                                \n   6            1          15         16 \
                                \n   7            2          16         19 \
                                \n   8            3          17         21 \
                                \n   9            4          18         23 \
                                \n  10            5 \
                                \n\nYou now have \
                                \nDexterity:  %i (%i)   Strength:  %i (%i)   Toughness: %i (%i)\
                                \nPerception: %i (%i)   Willpower: %i (%i)   Charisma:  %i (%i)\
                                \nYou have %i points left to spend \
                                \nPlease enter an attribute modification (s 15), "table", or "done"'\
                                % (self.stats['d'], (self.stats['d']+ self.statMod['d']), self.stats['s'], \
                                        (self.stats['s']+ self.statMod['s']), self.stats['t'], (self.stats['t']+ self.statMod['t']), \
                                        self.stats['p'],(self.stats['p']+ self.statMod['p']), self.stats['w'],\
                                        (self.stats['w']+ self.statMod['w']), self.stats['c'],(self.stats['c']+ self.statMod['c']), \
                                        self.stats['points']))
            elif line == 'done':
                
                # modified for race here
    
                if self.race == 'dwarf':
                    self.stats['s'] += 2
                    self.stats['t'] += 3
                    self.stats['c'] -= 1
                
                elif self.race == 'elf':
                    self.stats['d'] += 2
                    self.stats['t'] -= 2
                    self.stats['p'] += 1
                    self.stats['w'] += 1
                    self.stats['c'] += 1
                    
                elif self.race == 'human':
                    pass
                
                elif self.race == 'obsidiman':
                    self.stats['d'] -= 2
                    self.stats['s'] += 6
                    self.stats['t'] += 4
                    self.stats['p'] -= 1
                    self.stats['c'] -= 1
                
                elif self.race == 'ork':
                    self.stats['d'] -= 1
                    self.stats['s'] += 3
                    self.stats['t'] += 1
                    self.stats['w'] -= 1
                    self.stats['c'] -= 1
                    
                elif self.race == 'troll':
                    self.stats['s'] += 4
                    self.stats['t'] += 2
                    self.stats['p'] -= 1
                    self.stats['w'] += 1
                
                elif self.race == 't\'skrang':
                    self.stats['d'] += 1
                    self.stats['t'] += 1
                    self.stats['c'] += 1
                    
                elif self.race == 'windling':
                    self.stats['d'] += 1
                    self.stats['s'] -= 4
                    self.stats['t'] -= 3
                    self.stats['p'] += 1
                    self.stats['c'] += 2         
    
                self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
                                    % (self.stats['d'], self.stats['s'], self.stats['t'], self.stats['p'], self.stats['w'], self.stats['c'])
                
                # are now able to set attribute dependent traits
                doCreateCharacterAttributeDependendentTraits(self)
                
                self.setState(self.doCreateCharacterDescription)
            elif line[0] in ["d", "s", "t", "p", "w", "c"]:
                try:
                    if int(line[2:]) in range(2,19):
                        # a flag to make sure min max rules apply
                        ok = 1
                        
                        # need to check min and max stats for race
                        if self.race in ["obsidiman", "troll", "windling"]:
                            if self.race == 'obsidiman':
                                if line[0] == 's':
                                    if int(line[2:]) < 9:
                                        self.sendLine('Sorry, that would be below the minimum strength for an obsidiman.')
                                        ok = 0
                            elif self.race == 'troll':
                                if line[0] == 's':
                                    if int(line[2:]) < 7:
                                        self.sendLine('Sorry, that would be below the minimum strength for a troll.')
                                        ok = 0
                                if line[0] == 't':
                                    if int(line[2:]) < 9:
                                        self.sendLine('Sorry, that would be below the minimum toughness for a troll.')
                                        ok = 0
                            else: # must be 'windling':
                                if line[0] == 's':
                                    if line[2:] > 15:
                                        self.sendLine('Sorry, that would be above the maximum strength for a windling.')
                                        ok = 0
                        if ok == 1:
                            #calculate the number of points it will cost
                            #these next 2 lines shoudn't be this complicated...must be missing something
                            expression = compile("self.pointCost['" + line[2:] + "']", '', 'eval')
                            pointModifier = eval(expression)
                            #check to see if they have enough points left
                            #if self.stats['points'] + pointModifier >= 0:
                            
                            #first add back old value
                            expression = compile("self.stats['" + line[0] + "']", '', 'eval')
                            oldValue = eval(expression)
                            expression = compile("self.pointCost['" + str(oldValue) + "']", '', 'eval')
                            oldpointModifier = eval(expression)
                            pointModifier = pointModifier + -(oldpointModifier)
                            if self.stats['points'] + pointModifier >= 0:
                                #update attribute
                                self.stats[line[0]] = int(line[2:])
                                #remove points
                                self.stats['points'] = self.stats['points'] + pointModifier
                                self.sendLine('Attribute altered')
                            else:
                                self.sendLine('Not enough points to do that')
                    else:
                        self.sendLine('Invalid attribute assignment - minimum 2 and maximum 18. Please try again')
                except:
                    self.sendLine('Invalid attribute assignment. Please try again')
    
        else:
            self.sendLine('Please enter an attribute modification (s = 15), "table", or "done"')
    
    doCreateCharacterStats.prompt = ''
    
    def doCreateCharacterAttributeDependendentTraits(self):
        defenseRating = [0,2,3,3,4,4,4,5,5,6,6,7,7,7,8,8,9,9,10,10,10,11,11,12,12,13,13,13,14,14,15]
        movementFull = [0,25,28,30,32,35,38,40,43,48,50,54,57,60,65,70,75,80,85,90,100,110,120,130,140,150,160,170,180,200,220]
        movementCombat = [0,13,14,15,16,18,19,20,22,24,25,27,29,30,33,35,38,40,43,45,50,55,60,65,70,75,80,80,85,90,100,110]
        maxCarry = [0,10,15,20,25,30,35,40,50,60,70,80,90,105,125,145,165,200,230,270,315,360,430,500,580,675,790,920,1075,1200,1450]   
        maxLift = [0,20,30,40,50,65,75,85,100,115,135,160,185,210,250,290,310,400,460,540,630,735,860,1000,1160,1350,1580,1840,2150,2500,2900]
        deathRating = [0,19,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40,42,43,44,46,47,48,50,51,52,54,55,56,58]
        woundThreshold = [0,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,13,14,14,15,15,15,16,16,17]
        unconsciousRating = [0,10,11,13,14,15,17,18,19,21,22,24,26,27,28,29,31,32,34,35,36,39,40,41,43,44,45,47,48,49,51]
        recoveryTests = [0,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5]
        mysticArmor = [0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7]
        karma = {'dwarf':(6, 10, 5, 25), 'elf':(6, 10, 5, 25), 'human':(8, 6, 10, 40),
            'obsidiman':(4, 10, 5, 20), 'ork':(8, 7, 10, 40), 'troll':(4, 10, 5, 20),
            't\'skrang':(6, 8, 5, 25), 'windling':(10, 5, 15, 60)}
    
        
        if race == "obsidiman": # increased wound threshold and increased physical armor
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
                % (defenseRating[self.stats['d']], defenseRating[self.stats['p']], defenseRating[self.stats['c']], \
                   maxCarry[self.stats['s']], \
                   maxLift[self.stats['s']], deathRating[self.stats['t']], woundThreshold[self.stats['t']]+3, \
                   unconsciousRating[self.stats['t']], recoveryTests[self.stats['t']], mysticArmor[self.stats['w']])
                
        elif race == "windling": # increased physical defense
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
                % (defenseRating[self.stats['d']]+2, defenseRating[self.stats['p']], defenseRating[self.stats['c']], \
                   maxCarry[self.stats['s']], \
                   maxLift[self.stats['s']], deathRating[self.stats['t']], woundThreshold[self.stats['t']], \
                   unconsciousRating[self.stats['t']], recoveryTests[self.stats['t']], mysticArmor[self.stats['w']]) 
    
        else:                                        
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
                % (defenseRating[self.stats['d']], defenseRating[self.stats['p']], defenseRating[self.stats['c']], \
                   maxCarry[self.stats['s']], \
                   maxLift[self.stats['s']], deathRating[self.stats['t']], woundThreshold[self.stats['t']], \
                   unconsciousRating[self.stats['t']], recoveryTests[self.stats['t']], mysticArmor[self.stats['w']])    
        
        # now do movementFull, movementCombat, flyingcombat, flyingnormal based off of race
        # also do karmadice, karmacost, karmacurrent, karmamax
        if self.race == 'dwarf':
            if self.stats['d'] < 5:
                self.stats['d'] = 5
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']-2], movementCombat[self.stats['d']-2], \
               0, 0, karma['dwarf'][0], karma['dwarf'][1], karma['dwarf'][2], karma['dwarf'][3])
        
        elif self.race == 'elf':
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']+1], movementCombat[self.stats['d']+1], \
               0, 0, karma['elf'][0], karma['elf'][1], karma['elf'][2], karma['elf'][3])
            
        elif self.race == 'human':
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']], movementCombat[self.stats['d']], \
               0, 0, karma['human'][0], karma['human'][1], karma['human'][2], karma['human'][3])
        
        elif self.race == 'obsidiman':
            if self.stats['d'] < 6:
                self.stats['d'] = 6
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']-3], movementCombat[self.stats['d']-3], \
               0, 0, karma['obsidiman'][0], karma['obsidiman'][1], karma['obsidiman'][2], karma['obsidiman'][3])
        
        elif self.race == 'ork':
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']+1], movementCombat[self.stats['d']+1], \
               0, 0, karma['ork'][0], karma['ork'][1], karma['ork'][2], karma['ork'][3])
            
        elif self.race == 'troll':
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']+2], movementCombat[self.stats['d']+2], \
               0, 0, karma['troll'][0], karma['troll'][1], karma['troll'][2], karma['troll'][3])
        
        elif self.race == 't\'skrang':
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[self.stats['d']], movementCombat[self.stats['d']], \
               0, 0, karma['t\'skrang'][0], karma['t\'skrang'][1], karma['t\'skrang'][2], karma['t\'skrang'][3])
            
        elif self.race == 'windling':
            modDex = 0
            if self.stats['d'] < 11:
                modDex = 11
            else:
                modDex = self.stats['d']    
            self.insertStatement = self.insertStatement + '%i\',\'%i\',\'%i\',\'%i\',\'' \
            % (movementFull[modDex], movementCombat[modDex], \
                movementFull[self.stats['d']+2], movementCombat[self.stats['d']+2],
                karma['windling'][0], karma['windling'][1], karma['windling'][2], karma['windling'][3])
            
       
        # insert inititive - will just put step in here now
        self.insertStatement = self.insertStatement + '%i\',\'' % (self.stats['d'])
        
        # insert recovery dice - will just put step in here for now
        self.insertStatement = self.insertStatement + '%i\',\'' % (self.stats['t'])
        
        # insert NOW into datelaston
        self.insertStatement = self.insertStatement + '%s\',\'' % (time.ctime())
        
        # go ahead an insert all default values here
        # spousename,age,circle, normalarmor, damage, wound, bloodmagic, legendunspent, legendtotal, money, isbot, roomid
        
        #need to increase the physical armor of obsidimen
        if self.race == 'obsidiman':
            self.insertStatement = self.insertStatement + '%s\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\', \
                               \'%i\',\'%i\',\'%i\',\'' % ('none', 20, 1, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1)
        
        else:
            self.insertStatement = self.insertStatement + '%s\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\',\'%i\', \
                               \'%i\',\'%i\',\'%i\',\'' % ('none', 20, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1) 
    
    
    def doCreateCharacterDescription(self, line):
        "Create a new character password for the game"
        if line:
            self.insertStatement = self.insertStatement + "%s\')" % (string.replace(line,"'","\\'"))
            try:
                #db = MySQLdb.connect("localhost", "code", "Oicu812@2", "earthdawndb")
                #cursor = db.cursor()
              
                gv.cursor.execute(self.insertStatement)
                result = gv.cursor.rowcount
                try:
                    if result >= 1:
                        self.doloadPlayer(self.user)
                    else: #username and password don't match
                        self.setState = self.doInvalid
                except: #didn't get anything from DB - username doesn't exist
                    self.doInvalid(line)
            except: #DB not running
                self.doInvalid(line)
            #self.doloadPlayer(self.user)
        else:
            self.sendLine('Please enter a description for your character')
    doCreateCharacterDescription.prompt = 'Please enter a description for your character'